﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace CPETwit.WPFClient.CustomComponent
{
    public class CustomTextBox : TextBox
    {
        public static readonly DependencyProperty ProcessedTextProperty =
            DependencyProperty.Register("ProcessedText", typeof(string), typeof(CustomTextBox),
            new PropertyMetadata(string.Empty, ProcessedTextPropertyChangedCallback));

        private static void ProcessedTextPropertyChangedCallback(DependencyObject dependencyObject, 
            DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            CustomTextBox customTextBox = dependencyObject as CustomTextBox;
            if (customTextBox == null) return;
            string text = (string)dependencyPropertyChangedEventArgs.NewValue;
            if (string.IsNullOrEmpty(text))
            {
                customTextBox.ApplyStyle(text);
                text = customTextBox.DefaultText;
            }
            customTextBox.SetValue(TextProperty, text);
        }

        public string DefaultText { get; set; }
        public string ProcessedText
        {
            get
            {
                return (string)GetValue(TextProperty);
            }
            set
            {
                SetValue(ProcessedTextProperty, value);
            }
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            ProcessTextOnGotFocus();            
            base.OnGotFocus(e);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            ProcessTextOnLostFocus();
            ProcessedText = Text;
            base.OnLostFocus(e);
        }

        private void ProcessTextOnLostFocus()
        {
            ApplyStyle(Text);
            if (string.IsNullOrEmpty(Text))
                Text = DefaultText;
        }

        private void ProcessTextOnGotFocus()
        {
            ApplyStyle(Text);
            if (Text == DefaultText)
                Text = string.Empty;
        }

        public void ApplyStyle(string text)
        {
            if (string.IsNullOrEmpty(text)) 
                ApplyDefaultStyle(text);
            else 
                ApplyNormalStyle();
        }

        private void ApplyDefaultStyle(string text)
        {
            FontStyle = FontStyles.Italic;
        }
        private void ApplyNormalStyle()
        {
            FontStyle = FontStyles.Normal;
        }
    }
}
